package com.example.interview.ch03;

/**
 * synchronized(this)
 *
 * @author anin
 * @date 2022/4/27 10:08 AM
 */
public class Test1 {

    /*
     *  synchronized(this)
     *
     * 当一个线程访问ObjectService的一个synchronized (this)同步代码块时，
     * 其它线程对同一个ObjectService中其它的synchronized (this)同步代码块的访问将是堵塞，
     * 这说明synchronized (this)使用的对象监视器是一个，
     * 对其他线程的同一个ObjectService中的不加锁方法不受影响。
     *
     * A begin time=1651025515208
     * C begin time=1651025515211
     * C end   time=1651025515211
     * A end   time=1651025517214
     * B begin time=1651025517218
     * B end   time=1651025517218
     */

    public static void main(String[] args) {
        ObjectService service = new ObjectService();
        new Thread(()->{
            service.serviceMethodA();
        }).start();
        new Thread(()->{
            service.serviceMethodB();
        }).start();
        new Thread(()->{
            service.serviceMethodC();
        }).start();

    }
}

class ObjectService {
    public void serviceMethodA() {
        try {
            synchronized (this) {
                System.out.println("A begin time=" + System.currentTimeMillis());
                Thread.sleep(2000);
                System.out.println("A end   time=" + System.currentTimeMillis());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void serviceMethodB() {
        synchronized (this) {
            System.out.println("B begin time=" + System.currentTimeMillis());
            System.out.println("B end   time=" + System.currentTimeMillis());
        }

    }

    public void serviceMethodC() {
        System.out.println("C begin time=" + System.currentTimeMillis());
        System.out.println("C end   time=" + System.currentTimeMillis());
    }

}